<template>
  <div>
    <el-dialog
      :model-value="props.dialogVisible"
      :title="props.formStatus === 1 ? '编辑账号' : '新增账号'"
      width="500px"
      :close-on-click-modal="false"
      :before-close="handleClose">
      <el-form ref="accountFormRef" :model="accountForm" :rules="accountFormRules" label-width="100px" @submit.prevent>
        <el-form-item label="所属项目：" prop="pid">
          <el-tree-select
          v-model="accountForm.pid"
          node-key="pid"
          :data="treeData"
          :props="defaultProps"
          :render-after-expand="false"
          check-strictly
          clearable
          placeholder="请选择项目"
          style="width: 100%;"/>
        </el-form-item>
        <el-form-item label="姓名：" prop="userAlias">
          <el-input v-model="accountForm.userAlias" clearable placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="账号：" prop="username">
          <el-input v-model="accountForm.username" clearable placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="手机号码：" prop="phoneNum">
          <el-input v-model="accountForm.phoneNum" :maxlength="11" clearable placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input v-model="accountForm.email" clearable placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="角色：" prop="roleId">
          <el-select v-model="accountForm.roleId" clearable placeholder="请选择角色" style="width: 100%;">
            <el-option
              v-for="item in roleIdOptions"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注：" prop="info">
          <el-input v-model="accountForm.info" clearable placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit(accountFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="AccountModifyForm">
import { ref, reactive, watch, ComponentInternalInstance, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { accountInsert, accountUpdate } from '@/api/account-manage'
import { projectList } from '@/api/project-manage'
import { roleList } from '@/api/role-manage'

const { proxy } = getCurrentInstance() as ComponentInternalInstance

const emit = defineEmits(['submit', 'update:dialogVisible'])
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  formStatus: {
    type: Number,
    default: 0
  },
  formData: {
    type: Object,
    default: {}
  }
})

const defaultProps = {
  children: 'projectTree',
  label: 'projectName'
}
const roleIdOptions = ref<any>([])
const treeData = ref<any>([])
const accountForm = reactive({
  id: -1,
  pid: '',
  userAlias: '',
  username: '',
  phoneNum: '',
  email: '',
  roleId: '',
  info: '',
})
const accountFormRef = ref<FormInstance>()
const accountFormRules = reactive<FormRules>({
  pid: [
    { required: true, message: '请选择项目！' }
  ],
  userAlias: [
    { required: true, message: '请输入姓名！' }
  ],
  username: [
    { required: true, message: '请输入账号！' }
  ],
  phoneNum: [
    { required: true, message: '请输入手机号码！' }
  ],
  email: [
    { required: true, message: '请输入邮箱！' }
  ],
  roleId: [
    { required: true, message: '请选择角色！' }
  ]
})

watch(() => props.dialogVisible, async (newVal) => {
  if (newVal) {
    getProjectData()
    getRoleData()
    if (props.formStatus === 1) {
      accountForm.id = props.formData.id
      accountForm.pid = props.formData.pid
      accountForm.userAlias = props.formData.userAlias
      accountForm.username = props.formData.username
      accountForm.phoneNum = props.formData.phoneNum
      accountForm.email = props.formData.email
      accountForm.roleId = props.formData.roleId
      accountForm.info = props.formData.info
    }
  }
})

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 关闭弹窗
const handleClose = () => {
  resetForm(accountFormRef.value)
  proxy?.$emit('update:dialogVisible', false)
}

// 提交表单
const handleSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid, fields) => {
    if (valid) {
      if (props.formStatus === 0) {
        let { id, ...params } = accountForm
        await accountInsert(params).then((res: any) => {
          if (res.code === 0) {
            ElMessage.success(`新增成功！`)
            emit('submit')
            handleClose()
          } else {
            ElMessage.error(`${res.msg}`)
          }
        }).catch(err => {
          console.log(err)
        })
      } else {
        let params = Object.assign({}, accountForm)
        await accountUpdate(params).then((res: any) => {
          if (res.code === 0) {
            ElMessage.success(`编辑成功！`)
            emit('submit')
            handleClose()
          } else {
            ElMessage.error(`${res.msg}`)
          }
        }).catch(err => {
          console.log(err)
        })
      }
    }
  })
}

// 获取项目树表格数据
const getProjectData = async () => {
  await projectList().then((res: any) => {
    if (res.code === 0) {
      treeData.value = [res.data]
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
}

// 获取角色列表
const getRoleData = async () => {
  await roleList().then((res: any) => {
    if (res.code === 0) {
      roleIdOptions.value = [...res.list]
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
}
</script>

<style lang="stylus" scoped>

</style>
